$(function () {
    load();
});
const openImg=(img)=>{
    layer.open({
        type: 1,
        area: ['50%', '50%'],
        title: '图片预览',
        content: `<img style="width: 100%;height: 100%" src="${img}">`
    });
}
const openS = (item, e) => {
    let mytr = $(e).parent().parent().parent()
    let d = JSON.parse(item.replaceAll("|", "\""))
    if ($(e).hasClass("layui-icon-triangle-r")) {
        let mydiv = ``
        d.voList.forEach(item => {
            mydiv += `
    <div class="layui-form-item">
            <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
                <label class="layui-form-label">商品规格</label>
                <div class="layui-input-block layui-input-block1">
					 ${item.name}
                </div>
            </div>
            <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
				<label class="layui-form-label">商品价格</label>
				<div class="layui-input-block layui-input-block1">
				 ${item.price}
				</div>

            </div>
            <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
                <label class="layui-form-label">团购价格</label>
                <div class="layui-input-block layui-input-block1">
                    ${item.originalPrice}
                </div>
            </div>
            <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
                <label class="layui-form-label">拼团价格</label>
                <div class="layui-input-block layui-input-block1">
                    ${item.groupPrice}
                </div>
            </div>
        </div>  
			`
        })
        //当前的tr
        $(mytr).after(`
		<tr class="myTr">
		<td colspan="12" class="el-table__cell el-table__expanded-cell"> 
			<div class="layui-form-item"> 
                <label class="layui-form-label">商品图片</label>
                <div class="layui-input-block layui-input-block1"> 
					  <img class="myImg" width="100" height="100" src="${d.image}" onclick="openImg('${d.image}')">
                </div>
            </div>  
		    <div class="layui-form-item"> 
		     <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-block layui-input-block1">
					 ${d.name}
                </div>
            </div>
             <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
                <label class="layui-form-label">商品状态</label>
                <div class="layui-input-block layui-input-block1">
					 ${d.prodStatus == 1 ? '上架' : '下架'}
                </div>
            </div> 
            <div class="layui-inline" style="width: calc((100% - 55px) / 4);">
                <label class="layui-form-label">审核状态</label>
                <div class="layui-input-block layui-input-block1">
					 ${d.checkStatus == 1 ? '已通过' : d.checkStatus == 2 ? '已拒绝' : '待审核'}
                </div>
            </div>  
            </div> 
			${mydiv} 
			  <div class="layui-form-item"> 
                <label class="layui-form-label">创建时间</label>
                <div class="layui-input-block layui-input-block1">
					  ${d.createTime}
                </div>
            </div>  
            <div class="layui-form-item"> 
                <label class="layui-form-label">拒绝原因</label>
                <div class="layui-input-block layui-input-block1">
					 ${null!=d.checkResult?d.checkResult:'-'}
                </div>
            </div>    
		 </td></tr>
		`)
        $(e).removeClass('layui-icon-triangle-r')
        $(e).addClass('layui-icon-triangle-d')
    } else {
        $(e).removeClass('layui-icon-triangle-d')
        $(e).addClass('layui-icon-triangle-r')
        $(mytr).next().remove()
    }
}
var pages = 1;

function load() {
    layui.use(['table', 'dropdown', 'form'], function () {
        var table = layui.table,
            form = layui.form,
            $ = layui.$;

        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            , method: "get"
            , contentType: 'multipart/form-data'
            , url: "/jzweb/jazGroupProd/selGroupProdList"
            , cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 10
            }
            , request: {
                pageName: 'current',
                limitName: 'size'
            }
            , where: {
                name: $("#username").val(),
            }
            , defaultToolbar: false
            , loading: true
            , cols: [[
                {
                    field: "",
                    title:'',
                    align: 'center',
                    maxWidth: 30,
                    templet:function (d) {
                        let moldyd={
                            voList:d.voList,
                            image:d.image,
                            name:d.name,
                            checkResult:d.checkResult,
                            createTime:d.createTime,
                            checkStatus:d.checkStatus,
                            prodStatus:d.prodStatus,
                        }
                        let myd = JSON.stringify(moldyd).replaceAll("\"", "|")
                        return `<i class="layui-icon myIcons layui-icon-triangle-r"  onclick='openS("${myd}",this)'></i>`
                    }
                },
                {
                    field: 'name',
                    title: '商品名称',
                    align: 'center',
                    templet: function (d) {
                        return  `<span>${d.name}</span>`
                    }
                },
                {
                    field: '',
                    title: '商品规格',
                    align: 'center',
                    width:40,
                    templet: function (d) {
                        if (null != d.voList && d.voList.length > 0) {
                            return `<span>${d.voList[0].name}</span>`
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    field: '',
                    title: '商品价格',
                    align: 'center',
                    width:40,
                    templet: function (d) {
                        if (null != d.voList && d.voList.length > 0) {
                            return `<span>${d.voList[0].price}</span>`
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    field: '',
                    title: '团购价格',
                    align: 'center',
                    width:40,
                    templet: function (d) {
                        if (null != d.voList && d.voList.length > 0) {
                            return `<span>${d.voList[0].originalPrice}</span>`
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    field: '',
                    title: '拼团价格',
                    align: 'center',
                    width:40,
                    templet: function (d) {
                        if (null != d.voList && d.voList.length > 0) {
                            return `<span>${d.voList[0].groupPrice}</span>`
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    align: 'center',
                    templet:function (d) {
                        return `<span>${d.createTime}</span>`
                    }
                },
                {
                    field: 'prodStatus',
                    title: '商品状态',
                    align: 'center',
                    width:40,
                    templet: function (d) {
                        if (d.prodStatus == 1) {
                            return '<span class="label label-primary">上架</span>';
                        } else if (d.prodStatus == 0) {
                            return '<span class="label label-warning">下架</span>';
                        }
                    }
                },
                {
                    field: 'checkStatus',
                    title: '审核状态',
                    align: 'center',
                    width:40,
                    templet: function (d) {
                        if (d.checkStatus == 1) {

                            return '<span class="label label-primary">已通过</span>';
                        } else if (d.checkStatus == 2) {
                            return '<span class="label label-warning">已拒绝</span>';
                        } else {
                            return '<span class="label label-warning">待审核</span>';
                        }
                    }
                },
                {
                    field: 'checkResult',
                    title: '拒绝原因',
                    align: 'center',
                    templet: function (d) {
                        if (null != d.checkResult && ''!=d.checkResult) {
                            return `<span>${d.checkResult}</span>`
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    field : 'checkbox',
                    title : '是否上架',
                    align : 'center',
                    width:40,
                    templet:(d)=>{
                        return upAndDownPrices?((d.prodStatus=='1'?` 
      <input type="checkbox" checked `:'<input type="checkbox" ')+` name="open"  value="${d.id}"
      title="上架|下架" myid="${d.id}" lay-skin="switch" lay-filter="switchTest" title="是否启用"> 
						`):(d.prodStatus=='1'?'<span class="label label-primary">上架</span>':'<span class="label label-warning">下架</span>')
                    }
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    templet: function (d) {
                        var e = '<a  class="btn btn-primary btn-sm ' + look_infor+ ' " href="#" mce_href="#" title="详情" onclick="lookInfo(\''
                            + d.id
                            + '\')"><i class="fa fa-send"></i></a> ';

                        var bj = '<a  class="btn btn-primary btn-sm ' +look_edit+  ' " href="#" mce_href="#" title="编辑" onclick="edit(\''
                            + d.id
                            + '\')"><i class="fa fa-edit"></i></a> ';

                        var ss = '<a class="btn btn-success btn-sm ' +look_remove+  ' " href="#" title="删除"  mce_href="#" onclick="remove(\''
                            + d.id
                            + '\')"><i class="fa fa-remove"></i></a>';

                        return e + bj  + ss;
                    }
                }
            ]]
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                if (res.code != 0) {

                    return false;
                }

                // let screen = [];
                // res.data.records.forEach(function (v,k){
                // 	if( v.auditStatus != 0 ){
                // 		screen.push(v);
                // 	}
                // })

                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {

            }

            , done: function (res) {
                form.render()
            }
        });
        form.on('switch(switchTest)', function(data){
            let id=$(data.othis[0].parentNode).find('input').attr('myid')
            var loadIndex = layer.load(0);
            AjaxGet('/jzweb/jazGroupProd/editStatus', {id}).then(function (response){
                parent.layer.msg("操作成功");
                layer.close(loadIndex)
                load();
            }).catch(error => {
                layer.msg(error.msg)
                layer.close(loadIndex)
                load();
            })




        })
        var $ = layui.$, active = {
            reload: function () {
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        name: $("#username").val(),
                    }
                });
            }
        };

        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


    });

}

$("#add").click(function () {

    let toIndex = layer.open({
        type: 2,
        title: '新增团购商品',
        maxmin: true,
        shadeClose: false,
        area: ['800px', '500px'],
        // content: '/userAunt/add'
        content: '/jzweb/jazGroupProd/add/add/0'
    });
    layer.full(toIndex);
})

function edit(id) {
    let toIndex = layer.open({
        type: 2,
        title: '团购商品编辑',
        maxmin: true,
        shadeClose: false,
        area: ['800px', '500px'],
        content: `/jzweb/jazGroupProd/add/edit/${id}`
    });
    layer.full(toIndex);
}
function lookInfo(id) {
    let toIndex = layer.open({
        type: 2,
        title: '团购商品详情',
        maxmin: true,
        shadeClose: false,
        area: ['800px', '500px'],
        content: `/jzweb/jazGroupProd/add/info/${id}`
    });
    layer.full(toIndex);
}

function remove(id) {

    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: '/jzweb/jazGroupProd/remove',
            type: "post",
            data: {
                'id': id
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    load();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}